package com.ec.project.controller;

import com.ec.project.service.FeiShuService;
import com.lark.oapi.core.request.EventReq;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.event.CustomEventHandler;
import com.lark.oapi.event.EventDispatcher;
import com.lark.oapi.sdk.servlet.ext.ServletAdapter;
import com.lark.oapi.service.im.ImService;
import com.lark.oapi.service.im.v1.model.P2MessageReceiveV1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class EventController {

    @Autowired
    private FeiShuService feiShuService;

    //1. 注册消息处理器
    private final EventDispatcher EVENT_DISPATCHER = EventDispatcher.newBuilder("AJA7geb0LJVnIs5W8PZjCe8JLFTsbhI4",
                    "C7NXk81wdnXhhGm3UDiQ5sZLIzc52mPf")
            .onP2MessageReceiveV1(new ImService.P2MessageReceiveV1Handler() {
                @Override
                public void handle(P2MessageReceiveV1 event) throws Exception {
                    feiShuService.hanldeMsg(event);
                }
            }).onCustomizedEvent("这里填入你要自定义订阅的 event 的 key,例如 out_approval", new CustomEventHandler() {
                @Override
                public void handle(EventReq event) {
                    System.out.println("body:" + new String(event.getBody()));
                    System.out.println("plain:" + event.getPlain());
                }
            })
            .build();
    //2. 注入 ServletAdapter 实例
    @Autowired
    private ServletAdapter servletAdapter;
    //3. 创建路由处理器
    @RequestMapping("/webhook/event")
    public void event(HttpServletRequest request, HttpServletResponse response)
            throws Throwable {
        //3.1 回调扩展包提供的事件回调处理器
        servletAdapter.handleEvent(request, response, EVENT_DISPATCHER);
    }
}